/**
 * 人物剖析专家智能体
 * 专门用于分析人物性格、动机和行为模式的智能助手
 */
import { BaseAgent } from '../core/BaseAgent';

interface Person {
  id: string;
  name: string;
  age?: number;
  gender?: string;
  occupation?: string;
  background?: string;
  relationships?: Array<{
    personId: string;
    type: string;
    description: string;
  }>;
  behaviors?: Array<{
    id: string;
    description: string;
    timestamp?: string;
    context?: string;
  }>;
  statements?: Array<{
    id: string;
    content: string;
    timestamp?: string;
    context?: string;
  }>;
}

interface ProfileAnalysisResult {
  analysis: string;
  confidence: number;
  personalityTraits?: Array<{
    trait: string;
    score: number;
    evidence: string;
  }>;
  motivationAnalysis?: {
    possibleMotives: Array<{
      motive: string;
      likelihood: number;
      reasoning: string;
    }>;
    primaryMotive?: string;
  };
  behaviorPatterns?: string[];
  relationshipAnalysis?: string;
  predictions?: string[];
}

export class ProfileAnalyzer extends BaseAgent {
  /**
   * 执行人物分析任务
   * @param input 输入数据，包含人物信息
   * @returns 分析结果
   */
  async execute(input: {
    person: Person;
    task?: string;
    focus?: string;
    context?: string;
  }): Promise<ProfileAnalysisResult> {
    try {
      console.log(`[ProfileAnalyzer] 开始分析人物：${input.person.name}`);
      
      // 根据任务类型执行不同的分析
      if (input.task === 'personality_analysis') {
        return this.analyzePersonality(input.person, input.context);
      } else if (input.task === 'motivation_analysis') {
        return this.analyzeMotivation(input.person, input.context);
      } else if (input.task === 'behavior_analysis') {
        return this.analyzeBehaviorPatterns(input.person);
      } else if (input.focus === 'relationships') {
        return this.analyzeRelationships(input.person);
      } else {
        // 默认执行全面分析
        return this.comprehensiveProfileAnalysis(input.person, input.context);
      }
    } catch (error) {
      console.error('[ProfileAnalyzer] 分析过程中出现错误:', error);
      return {
        analysis: `分析过程中出现错误: ${error instanceof Error ? error.message : String(error)}`,
        confidence: 0
      };
    }
  }

  /**
   * 分析人物性格
   * @param person 人物信息
   * @param context 上下文信息
   * @returns 性格分析结果
   */
  private analyzePersonality(person: Person, context?: string): ProfileAnalysisResult {
    const personalityTraits: ProfileAnalysisResult['personalityTraits'] = [];
    
    // 基于行为和陈述分析性格特征
    const behaviors = person.behaviors || [];
    const statements = person.statements || [];
    
    // 分析性格特征（这里使用简单的关键词匹配和模式识别）
    // 示例：分析是否冲动
    const impulsiveScore = this.calculateImpulsiveScore(behaviors, statements);
    if (impulsiveScore > 0) {
      personalityTraits.push({
        trait: '冲动性',
        score: impulsiveScore,
        evidence: this.findEvidenceForTrait(behaviors, statements, 'impulsive')
      });
    }
    
    // 分析是否细心
    const carefulScore = this.calculateCarefulScore(behaviors, statements);
    if (carefulScore > 0) {
      personalityTraits.push({
        trait: '细心程度',
        score: carefulScore,
        evidence: this.findEvidenceForTrait(behaviors, statements, 'careful')
      });
    }
    
    // 分析社交倾向
    const socialScore = this.calculateSocialScore(person.relationships || [], statements);
    if (socialScore > 0) {
      personalityTraits.push({
        trait: '社交倾向',
        score: socialScore,
        evidence: this.findEvidenceForTrait([], statements, 'social')
      });
    }
    
    // 生成分析报告
    let analysis = `## 人物性格分析报告\n\n`;
    analysis += `**分析对象**: ${person.name}\n`;
    if (person.occupation) analysis += `**职业**: ${person.occupation}\n`;
    if (context) analysis += `**分析场景**: ${context}\n\n`;
    
    analysis += `### 性格特征分析\n\n`;
    if (personalityTraits.length > 0) {
      personalityTraits.forEach(trait => {
        analysis += `- **${trait.trait}**: ${this.getTraitLevel(trait.score)} (${(trait.score * 100).toFixed(0)}%)\n`;
        analysis += `  *证据*: ${trait.evidence}\n\n`;
      });
    } else {
      analysis += `基于现有信息，无法确定明显的性格特征。建议收集更多关于行为和陈述的信息。\n`;
    }
    
    // 计算分析可信度
    const confidence = this.calculateConfidence(personalityTraits, behaviors, statements);
    
    return {
      analysis,
      confidence,
      personalityTraits
    };
  }

  /**
   * 分析人物动机
   * @param person 人物信息
   * @param context 上下文信息
   * @returns 动机分析结果
   */
  private analyzeMotivation(person: Person, context?: string): ProfileAnalysisResult {
    const possibleMotives: NonNullable<ProfileAnalysisResult['motivationAnalysis']>['possibleMotives'] = [];
    
    // 基于人物背景、关系和行为分析可能的动机
    
    // 分析财务动机
    const financialMotiveScore = this.analyzeFinancialMotivation(person);
    if (financialMotiveScore > 0) {
      possibleMotives.push({
        motive: '财务利益',
        likelihood: financialMotiveScore,
        reasoning: '基于人物的经济状况或财务相关行为分析'
      });
    }
    
    // 分析情感动机
    const emotionalMotiveScore = this.analyzeEmotionalMotivation(person);
    if (emotionalMotiveScore > 0) {
      possibleMotives.push({
        motive: '情感因素',
        likelihood: emotionalMotiveScore,
        reasoning: '基于人际关系和情感状态分析'
      });
    }
    
    // 分析权力动机
    const powerMotiveScore = this.analyzePowerMotivation(person);
    if (powerMotiveScore > 0) {
      possibleMotives.push({
        motive: '权力欲望',
        likelihood: powerMotiveScore,
        reasoning: '基于对控制和影响力的追求分析'
      });
    }
    
    // 分析复仇动机
    const revengeMotiveScore = this.analyzeRevengeMotivation(person);
    if (revengeMotiveScore > 0) {
      possibleMotives.push({
        motive: '复仇心理',
        likelihood: revengeMotiveScore,
        reasoning: '基于过去的冲突或伤害分析'
      });
    }
    
    // 按可能性排序
    possibleMotives.sort((a, b) => b.likelihood - a.likelihood);
    
    // 确定主要动机
    const primaryMotive = possibleMotives.length > 0 ? possibleMotives[0].motive : undefined;
    
    // 生成分析报告
    let analysis = `## 人物动机分析报告\n\n`;
    analysis += `**分析对象**: ${person.name}\n`;
    if (context) analysis += `**分析场景**: ${context}\n\n`;
    
    analysis += `### 可能的动机分析\n\n`;
    if (possibleMotives.length > 0) {
      possibleMotives.forEach((motive, index) => {
        analysis += `${index + 1}. **${motive.motive}**: ${this.getLikelihoodLevel(motive.likelihood)}\n`;
        analysis += `   *可能性*: ${(motive.likelihood * 100).toFixed(0)}%\n`;
        analysis += `   *推理依据*: ${motive.reasoning}\n\n`;
      });
      
      if (primaryMotive) {
        analysis += `**主要推测动机**: ${primaryMotive}\n`;
      }
    } else {
      analysis += `基于现有信息，无法确定明确的动机。建议收集更多背景信息和行为数据。\n`;
    }
    
    // 计算分析可信度
    const confidence = possibleMotives.length > 0 ? 
      possibleMotives.reduce((sum, m) => sum + m.likelihood, 0) / possibleMotives.length : 0.3;
    
    return {
      analysis,
      confidence,
      motivationAnalysis: {
        possibleMotives,
        primaryMotive
      }
    };
  }

  /**
   * 分析行为模式
   * @param person 人物信息
   * @returns 行为模式分析结果
   */
  private analyzeBehaviorPatterns(person: Person): ProfileAnalysisResult {
    const behaviorPatterns: string[] = [];
    const behaviors = person.behaviors || [];
    
    if (behaviors.length > 0) {
      // 分析时间模式
      const timePattern = this.analyzeTimePattern(behaviors);
      if (timePattern) {
        behaviorPatterns.push(timePattern);
      }
      
      // 分析反应模式
      const reactionPattern = this.analyzeReactionPattern(behaviors);
      if (reactionPattern) {
        behaviorPatterns.push(reactionPattern);
      }
      
      // 分析决策模式
      const decisionPattern = this.analyzeDecisionPattern(behaviors);
      if (decisionPattern) {
        behaviorPatterns.push(decisionPattern);
      }
    }
    
    // 生成分析报告
    let analysis = `## 行为模式分析报告\n\n`;
    analysis += `**分析对象**: ${person.name}\n\n`;
    
    analysis += `### 观察到的行为模式\n\n`;
    if (behaviorPatterns.length > 0) {
      behaviorPatterns.forEach((pattern, index) => {
        analysis += `${index + 1}. ${pattern}\n`;
      });
    } else {
      analysis += `基于现有信息，无法识别明显的行为模式。建议收集更多行为数据。\n`;
    }
    
    // 计算分析可信度
    const confidence = behaviorPatterns.length > 0 ? 0.8 : 0.3;
    
    return {
      analysis,
      confidence,
      behaviorPatterns
    };
  }

  /**
   * 分析人际关系
   * @param person 人物信息
   * @returns 关系分析结果
   */
  private analyzeRelationships(person: Person): ProfileAnalysisResult {
    const relationships = person.relationships || [];
    
    // 生成关系分析
    let analysis = `## 人际关系分析报告\n\n`;
    analysis += `**分析对象**: ${person.name}\n\n`;
    
    if (relationships.length > 0) {
      // 按关系类型分组
      const relationshipsByType = this.groupRelationshipsByType(relationships);
      
      analysis += `### 关系网络分析\n\n`;
      analysis += `共识别到 ${relationships.length} 段人际关系\n\n`;
      
      for (const [type, typeRelationships] of Object.entries(relationshipsByType)) {
        analysis += `**${type}关系** (${typeRelationships.length}人):\n`;
        typeRelationships.forEach(rel => {
          analysis += `- ${rel.personId}: ${rel.description}\n`;
        });
        analysis += `\n`;
      }
      
      // 分析关系质量
      const relationshipQuality = this.analyzeRelationshipQuality(relationships);
      analysis += `### 关系质量分析\n\n`;
      analysis += relationshipQuality + `\n`;
    } else {
      analysis += `没有找到相关的人际关系信息。\n`;
    }
    
    // 计算分析可信度
    const confidence = relationships.length > 0 ? 0.85 : 0.2;
    
    return {
      analysis,
      confidence,
      relationshipAnalysis: relationships.length > 0 ? '已完成关系网络分析' : '无关系信息'
    };
  }

  /**
   * 综合人物分析
   * @param person 人物信息
   * @param context 上下文信息
   * @returns 综合分析结果
   */
  private comprehensiveProfileAnalysis(person: Person, context?: string): ProfileAnalysisResult {
    // 执行各种分析
    const personalityResult = this.analyzePersonality(person, context);
    const motivationResult = this.analyzeMotivation(person, context);
    const behaviorResult = this.analyzeBehaviorPatterns(person);
    const relationshipResult = this.analyzeRelationships(person);
    
    // 生成综合分析报告
    let analysis = `## 人物综合分析报告\n\n`;
    analysis += `**分析对象**: ${person.name}\n`;
    if (context) analysis += `**分析场景**: ${context}\n\n`;
    
    // 整合各部分分析结果
    analysis += personalityResult.analysis + `\n`;
    analysis += motivationResult.analysis + `\n`;
    analysis += behaviorResult.analysis + `\n`;
    analysis += relationshipResult.analysis + `\n`;
    
    // 生成预测
    const predictions = this.generateBehaviorPredictions(
      personalityResult.personalityTraits || [],
      motivationResult.motivationAnalysis || {},
      behaviorResult.behaviorPatterns || []
    );
    
    if (predictions.length > 0) {
      analysis += `### 行为预测\n\n`;
      predictions.forEach((prediction, index) => {
        analysis += `${index + 1}. ${prediction}\n`;
      });
    }
    
    // 计算综合可信度
    const confidence = (
      personalityResult.confidence + 
      motivationResult.confidence + 
      behaviorResult.confidence + 
      relationshipResult.confidence
    ) / 4;
    
    return {
      analysis,
      confidence,
      personalityTraits: personalityResult.personalityTraits,
      motivationAnalysis: motivationResult.motivationAnalysis,
      behaviorPatterns: behaviorResult.behaviorPatterns,
      relationshipAnalysis: relationshipResult.relationshipAnalysis,
      predictions
    };
  }

  // 辅助方法 - 性格分析相关
  private calculateImpulsiveScore(behaviors: Person['behaviors'], statements: Person['statements']): number {
    // 简单的关键词匹配逻辑
    const impulsiveKeywords = ['冲动', '仓促', '不假思索', '立即', '突然'];
    let score = 0;
    
    if (behaviors) {
      behaviors.forEach(behavior => {
        if (impulsiveKeywords.some(keyword => behavior.description.includes(keyword))) {
          score += 0.1;
        }
      });
    }
    
    if (statements) {
      statements.forEach(statement => {
        if (impulsiveKeywords.some(keyword => statement.content.includes(keyword))) {
          score += 0.05;
        }
      });
    }
    
    return Math.min(1.0, score);
  }

  private calculateCarefulScore(behaviors: Person['behaviors'], statements: Person['statements']): number {
    // 简单的关键词匹配逻辑
    const carefulKeywords = ['仔细', '谨慎', '考虑', '分析', '计划'];
    let score = 0;
    
    if (behaviors) {
      behaviors.forEach(behavior => {
        if (carefulKeywords.some(keyword => behavior.description.includes(keyword))) {
          score += 0.1;
        }
      });
    }
    
    if (statements) {
      statements.forEach(statement => {
        if (carefulKeywords.some(keyword => statement.content.includes(keyword))) {
          score += 0.05;
        }
      });
    }
    
    return Math.min(1.0, score);
  }

  private calculateSocialScore(relationships: Person['relationships'], statements: Person['statements']): number {
    // 基于关系数量和社交相关陈述计算
    let score = relationships.length * 0.05;
    
    const socialKeywords = ['朋友', '聚会', '社交', '交流', '沟通'];
    if (statements) {
      statements.forEach(statement => {
        if (socialKeywords.some(keyword => statement.content.includes(keyword))) {
          score += 0.05;
        }
      });
    }
    
    return Math.min(1.0, score);
  }

  private findEvidenceForTrait(behaviors: Person['behaviors'], statements: Person['statements'], traitType: string): string {
    // 查找支持特定性格特征的证据
    let evidence = '无具体证据';
    
    // 简单实现，返回第一条相关行为或陈述
    if (behaviors) {
      for (const behavior of behaviors) {
        if (this.isBehaviorRelatedToTrait(behavior, traitType)) {
          evidence = behavior.description.substring(0, 100) + '...';
          break;
        }
      }
    }
    
    if (evidence === '无具体证据' && statements) {
      for (const statement of statements) {
        if (this.isStatementRelatedToTrait(statement, traitType)) {
          evidence = statement.content.substring(0, 100) + '...';
          break;
        }
      }
    }
    
    return evidence;
  }

  private isBehaviorRelatedToTrait(behavior: Person['behaviors'][0], traitType: string): boolean {
    // 判断行为是否与特定性格特征相关
    const traitKeywords: Record<string, string[]> = {
      'impulsive': ['冲动', '仓促', '立即'],
      'careful': ['仔细', '谨慎', '考虑'],
      'social': ['朋友', '聚会', '交流']
    };
    
    const keywords = traitKeywords[traitType] || [];
    return keywords.some(keyword => behavior.description.includes(keyword));
  }

  private isStatementRelatedToTrait(statement: Person['statements'][0], traitType: string): boolean {
    // 判断陈述是否与特定性格特征相关
    const traitKeywords: Record<string, string[]> = {
      'impulsive': ['冲动', '立即', '突然'],
      'careful': ['仔细', '谨慎', '分析'],
      'social': ['朋友', '社交', '沟通']
    };
    
    const keywords = traitKeywords[traitType] || [];
    return keywords.some(keyword => statement.content.includes(keyword));
  }

  private getTraitLevel(score: number): string {
    if (score >= 0.8) return '非常高';
    if (score >= 0.6) return '较高';
    if (score >= 0.4) return '中等';
    if (score >= 0.2) return '较低';
    return '非常低';
  }

  // 辅助方法 - 动机分析相关
  private analyzeFinancialMotivation(person: Person): number {
    // 简单的财务动机分析
    const financialKeywords = ['钱', '财产', '经济', '债务', '贫困', '富有'];
    let score = 0;
    
    if (person.background && financialKeywords.some(keyword => person.background.includes(keyword))) {
      score += 0.3;
    }
    
    if (person.behaviors) {
      person.behaviors.forEach(behavior => {
        if (financialKeywords.some(keyword => behavior.description.includes(keyword))) {
          score += 0.2;
        }
      });
    }
    
    if (person.statements) {
      person.statements.forEach(statement => {
        if (financialKeywords.some(keyword => statement.content.includes(keyword))) {
          score += 0.15;
        }
      });
    }
    
    return Math.min(1.0, score);
  }

  private analyzeEmotionalMotivation(person: Person): number {
    // 简单的情感动机分析
    const emotionalKeywords = ['爱', '恨', '愤怒', '嫉妒', '伤心', '失望', '报复'];
    let score = 0;
    
    if (person.relationships) {
      person.relationships.forEach(rel => {
        if (emotionalKeywords.some(keyword => rel.description.includes(keyword))) {
          score += 0.2;
        }
      });
    }
    
    if (person.statements) {
      person.statements.forEach(statement => {
        if (emotionalKeywords.some(keyword => statement.content.includes(keyword))) {
          score += 0.15;
        }
      });
    }
    
    return Math.min(1.0, score);
  }

  private analyzePowerMotivation(person: Person): number {
    // 简单的权力动机分析
    const powerKeywords = ['控制', '权力', '领导', '决定', '支配', '权威'];
    let score = 0;
    
    if (person.occupation && ['领导', '经理', '主管', '官员'].some(title => person.occupation!.includes(title))) {
      score += 0.2;
    }
    
    if (person.behaviors) {
      person.behaviors.forEach(behavior => {
        if (powerKeywords.some(keyword => behavior.description.includes(keyword))) {
          score += 0.2;
        }
      });
    }
    
    if (person.statements) {
      person.statements.forEach(statement => {
        if (powerKeywords.some(keyword => statement.content.includes(keyword))) {
          score += 0.15;
        }
      });
    }
    
    return Math.min(1.0, score);
  }

  private analyzeRevengeMotivation(person: Person): number {
    // 简单的复仇动机分析
    const revengeKeywords = ['报复', '惩罚', '伤害', '对不起', '错误', '仇恨'];
    let score = 0;
    
    if (person.background && revengeKeywords.some(keyword => person.background.includes(keyword))) {
      score += 0.3;
    }
    
    if (person.relationships) {
      person.relationships.forEach(rel => {
        if (rel.description.includes('冲突') || rel.description.includes('敌对')) {
          score += 0.2;
        }
      });
    }
    
    if (person.statements) {
      person.statements.forEach(statement => {
        if (revengeKeywords.some(keyword => statement.content.includes(keyword))) {
          score += 0.2;
        }
      });
    }
    
    return Math.min(1.0, score);
  }

  private getLikelihoodLevel(likelihood: number): string {
    if (likelihood >= 0.8) return '非常可能';
    if (likelihood >= 0.6) return '很可能';
    if (likelihood >= 0.4) return '可能';
    if (likelihood >= 0.2) return '不太可能';
    return '可能性很低';
  }

  // 辅助方法 - 行为模式分析相关
  private analyzeTimePattern(behaviors: Person['behaviors']): string | null {
    // 简单的时间模式分析
    if (!behaviors || behaviors.length < 3) return null;
    
    // 这里只是示例，实际应该分析时间戳
    return '未能确定明确的时间模式（需要带时间戳的行为数据）';
  }

  private analyzeReactionPattern(behaviors: Person['behaviors']): string | null {
    // 简单的反应模式分析
    if (!behaviors || behaviors.length < 3) return null;
    
    const reactiveBehaviors = behaviors.filter(b => 
      b.description.includes('反应') || 
      b.description.includes('回应') || 
      b.context?.includes('面对')
    );
    
    if (reactiveBehaviors.length >= 2) {
      return `${person.name}在面对特定情况时表现出一定的反应模式`;
    }
    
    return null;
  }

  private analyzeDecisionPattern(behaviors: Person['behaviors']): string | null {
    // 简单的决策模式分析
    if (!behaviors || behaviors.length < 3) return null;
    
    const decisionBehaviors = behaviors.filter(b => 
      b.description.includes('决定') || 
      b.description.includes('选择') || 
      b.description.includes('判断')
    );
    
    if (decisionBehaviors.length >= 2) {
      return `${person.name}在做决策时表现出一定的模式`;
    }
    
    return null;
  }

  // 辅助方法 - 关系分析相关
  private groupRelationshipsByType(relationships: Person['relationships']): Record<string, Person['relationships']> {
    return relationships.reduce((groups, relationship) => {
      const type = relationship.type;
      if (!groups[type]) {
        groups[type] = [];
      }
      groups[type].push(relationship);
      return groups;
    }, {} as Record<string, Person['relationships']>);
  }

  private analyzeRelationshipQuality(relationships: Person['relationships']): string {
    // 简单的关系质量分析
    const positiveWords = ['良好', '友好', '支持', '信任', '爱'];
    const negativeWords = ['冲突', '敌对', '讨厌', '不信任', '恨'];
    
    let positiveCount = 0;
    let negativeCount = 0;
    
    relationships.forEach(rel => {
      if (positiveWords.some(word => rel.description.includes(word))) {
        positiveCount++;
      }
      if (negativeWords.some(word => rel.description.includes(word))) {
        negativeCount++;
      }
    });
    
    if (positiveCount > negativeCount) {
      return `${person.name}的人际关系总体较为积极，有${positiveCount}个积极关系`;
    } else if (negativeCount > positiveCount) {
      return `${person.name}的人际关系中存在较多冲突，有${negativeCount}个消极关系`;
    } else {
      return `${person.name}的人际关系质量较为平衡`;
    }
  }

  // 其他辅助方法
  private calculateConfidence(traits: ProfileAnalysisResult['personalityTraits'], behaviors: Person['behaviors'], statements: Person['statements']): number {
    // 基于数据量和特征明确性计算可信度
    let confidence = 0.5; // 基础可信度
    
    // 数据量权重
    const dataVolume = (behaviors?.length || 0) + (statements?.length || 0);
    confidence += Math.min(0.3, dataVolume * 0.05);
    
    // 特征明确性权重
    if (traits && traits.length > 0) {
      const avgTraitScore = traits.reduce((sum, trait) => sum + trait.score, 0) / traits.length;
      confidence += avgTraitScore * 0.2;
    }
    
    return Math.min(1.0, confidence);
  }

  private generateBehaviorPredictions(
    traits: ProfileAnalysisResult['personalityTraits'],
    motivation: NonNullable<ProfileAnalysisResult['motivationAnalysis']>,
    patterns: string[]
  ): string[] {
    const predictions: string[] = [];
    
    // 基于性格特征生成预测
    const impulsiveTrait = traits.find(t => t.trait === '冲动性');
    if (impulsiveTrait && impulsiveTrait.score > 0.7) {
      predictions.push('在压力情境下可能做出冲动决策');
    }
    
    const carefulTrait = traits.find(t => t.trait === '细心程度');
    if (carefulTrait && carefulTrait.score > 0.7) {
      predictions.push('在做重要决定时可能会仔细权衡利弊');
    }
    
    // 基于动机生成预测
    if (motivation.primaryMotive) {
      predictions.push(`基于${motivation.primaryMotive}的动机，可能会优先考虑相关利益`);
    }
    
    return predictions;
  }
}
